const fs = require('fs');
const path = require('path')
const request = require('request');
const compressing = require('compressing');

// 需要下载的CDN文件
const config = require('./src/config');
const child_process = require('child_process')
const tarball = require('npm-tarball')
let queue = 0;


const downFile = async(name,array,route) => {
  // 例： /\/axios-.+tgz$/
  const re = new RegExp(`\/${name}-.+tgz`, 'g')
  const arr = typeof array === 'string' ? JSON.parse(array) : array;
  const paths = `${path.resolve(__dirname)}/public`;
  for( item of arr){
    // 下载文件
    await new Promise ((res,rej) => {
      const src = route.replace(re,`/${name}-${item}.tgz`).replace('npmjs.org','cnpmjs.org');
      request(src,(error,respost,data) => {
        if(error){
          console.log('\033[31m ERROR: '+name+'下载失败 \033[39m');
          res();
          return false
        }
        console.log('\033[32m SUCCESS: 正在下载'+src+' \033[39m');
        compressing.tgz.uncompress(`./public/${name}/${item}/${item}.tgz`, `./public/${name}/${item}`).then(() => {
          console.log('\033[32m SUCCESS: '+name+'解压成功 \033[39m');
          res();
        }).catch(e => {
          console.log(`./public/${name}/${item}/${item}.tgz`);
          console.log('\033[31m ERROR: '+name+'解压失败 \033[39m');
          res();
        });
      }).pipe(fs.createWriteStream(`./public/${name}/${item}/${item}.tgz`));
    })
  }
  // 移动文件
  arr.forEach(item => {
    try {
      fs.accessSync(`./public/${name}/${item}/package/dist/${name}.js`, fs.constants.R_OK | fs.constants.W_OK);
      fs.renameSync(`${paths}/${name}/${item}/package/dist/${name}.js`, `${paths}/${name}/${item}/${name}.js`);
      fs.renameSync(`${paths}/${name}/${item}/package/dist/${name}.min.js`, `${paths}/${name}/${item}/${name}.min.js`);
    } catch (err) {
      console.log('\033[31m ERROR: 移动'+paths+'/'+name+'/'+item+'/package/dist/'+name+'.js时报错 \033[39m');
    }
  });
  queue = queue >= config.length ? queue : queue+1;
  if(queue == config.length){
    console.log('\033[32m SUCCESS: 全部下载完成 \033[39m');
  } else {
    check(config[queue]);
  }
}

// 下载相对应的版本号
const asyncReadFile = async (name,arr) => {
  tarball.resolveUri(name).then(data => {
    // 执行下载函数
    downFile(name,arr,data);
  })
};

// 创建文件夹
const mkdir = (names,arrs) => {
  const name = names;
  const arr = arrs;
  const src = `${path.resolve(__dirname)}/public/${name}`;
  if(!fs.existsSync(src)){
    console.log('\033[32m SUCCESS: 创建'+name+'文件夹 \033[39m');
    fs.mkdirSync(src)
  } else {
    console.log('\033[32m SUCCESS: 已存在'+name+'文件夹 \033[39m');
  }
  const data = arr ? JSON.parse(arr) : false;
  if(data && data.length > 0){
    data.forEach(element => {
      const childSrc = `${path.resolve(__dirname)}/public/${name}/${element}`;
      if(!fs.existsSync(childSrc)){
        console.log('\033[32m SUCCESS: 创建'+element+'文件夹 \033[39m');
        fs.mkdirSync(childSrc);
      } else {
        console.log('\033[32m SUCCESS: 已存在'+element+'文件夹 \033[39m');
      }
    });
  }
  // 下载文件
  asyncReadFile(name,arr);
}

// 获取所有CDN版本号
const check =   (item) => {
  console.log('\033[32m Progressive: 正在获取配置CDN所有版本 \033[39m');
    // 获取所有版本号
    child_process.exec(`npm view ${item} versions --json`,(err,stdout,stderr) => {
      if (err) {
        rej()
        return cb(err)
      }
      console.log('\033[32m SUCCESS: 获取'+item+'所有版本 \033[39m');
      mkdir(item,stdout);
    })
}


check(config[queue]);


